<template>
  <div class="positions-page">
    <div class="page-header">
      <h1>持仓管理</h1>
      <p>实时监控和管理当前持仓情况</p>
    </div>

    <div class="summary-cards" v-loading="summaryLoading">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="summary-card">
            <div class="card-content">
              <div class="card-icon total">
                <el-icon><Wallet /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ summary?.totalPositions || 0 }}</div>
                <div class="card-label">总持仓</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="summary-card">
            <div class="card-content">
              <div class="card-icon active">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ summary?.activePositions || 0 }}</div>
                <div class="card-label">活跃持仓</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="summary-card">
            <div class="card-content">
              <div class="card-icon margin">
                <el-icon><Money /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">${{ formatNumber(summary?.totalMargin || 0) }}</div>
                <div class="card-label">总保证金</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="summary-card">
            <div class="card-content">
              <div class="card-icon" :class="summary && summary.totalUnrealizedPnl >= 0 ? 'profit' : 'loss'">
                <el-icon><Opportunity /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value" :class="summary && summary.totalUnrealizedPnl >= 0 ? 'profit-text' : 'loss-text'">
                  ${{ formatNumber(summary?.totalUnrealizedPnl || 0) }}
                </div>
                <div class="card-label">未实现盈亏</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="summary-card">
            <div class="card-content">
              <div class="card-icon" :class="summary && summary.totalPnl >= 0 ? 'profit' : 'loss'">
                <el-icon><PieChart /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value" :class="summary && summary.totalPnl >= 0 ? 'profit-text' : 'loss-text'">
                  ${{ formatNumber(summary?.totalPnl || 0) }}
                </div>
                <div class="card-label">总盈亏</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="summary-card">
            <div class="card-content">
              <div class="card-icon" :class="getRiskLevelClass(summary?.riskLevel)">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ formatPercent(summary?.marginRatio || 0) }}</div>
                <div class="card-label">保证金率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-card class="positions-table-card">
      <template #header>
        <div class="card-header">
          <span>持仓列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData" :loading="tableLoading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="showBatchClose = true" :disabled="selectedPositions.length === 0">
              <el-icon><Close /></el-icon>
              批量平仓
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="positions" 
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
        class="positions-table"
        stripe
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="交易对" width="140">
          <template #default="{ row }">
            <div class="coin-info">
              <span class="coin-icon">{{ row.coinIcon }}</span>
              <div class="coin-details">
                <div class="coin-symbol">{{ row.symbol }}</div>
                <div class="coin-name">{{ row.coinName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="方向" width="80">
          <template #default="{ row }">
            <el-tag :type="row.side === 'long' ? 'success' : 'danger'" size="small">
              {{ row.side === 'long' ? '做多' : '做空' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="数量" prop="size" width="100">
          <template #default="{ row }">
            {{ formatNumber(row.size) }}
          </template>
        </el-table-column>
        
        <el-table-column label="开仓价格" width="120">
          <template #default="{ row }">
            ${{ formatPrice(row.entryPrice) }}
          </template>
        </el-table-column>
        
        <el-table-column label="当前价格" width="120">
          <template #default="{ row }">
            <span :class="getPriceChangeClass(row.entryPrice, row.currentPrice, row.side)">
              ${{ formatPrice(row.currentPrice) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="盈亏" width="140">
          <template #default="{ row }">
            <div class="pnl-info">
              <div :class="row.pnl >= 0 ? 'profit-text' : 'loss-text'">
                ${{ formatNumber(row.pnl) }}
              </div>
              <div class="pnl-percent" :class="row.pnl >= 0 ? 'profit-text' : 'loss-text'">
                ({{ formatPercent(row.pnlPercent / 100) }})
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="保证金" width="100">
          <template #default="{ row }">
            ${{ formatNumber(row.margin) }}
          </template>
        </el-table-column>
        
        <el-table-column label="杠杆" width="70">
          <template #default="{ row }">
            {{ row.leverage }}x
          </template>
        </el-table-column>
        
        <el-table-column label="强平价" width="120">
          <template #default="{ row }">
            <span class="liquidation-price">
              {{ row.liquidationPrice > 0 ? '$' + formatPrice(row.liquidationPrice) : '-' }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="策略" width="150">
          <template #default="{ row }">
            <div class="strategy-info">
              <div class="strategy-name">{{ row.strategyName }}</div>
              <div class="exchange-name">{{ row.exchangeName }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)" 
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="开仓时间" width="150">
          <template #default="{ row }">
            {{ formatDateTime(row.openTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                @click="editPosition(row)"
                :disabled="row.status !== 'active'"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
                             <el-button 
                 type="danger" 
                 size="small" 
                 @click="handleClosePosition(row)"
                 :disabled="row.status !== 'active'"
               >
                 <el-icon><Close /></el-icon>
                 平仓
               </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑持仓" 
      width="600px"
      :before-close="handleEditClose"
    >
      <el-form 
        :model="editForm" 
        :rules="editRules" 
        ref="editFormRef" 
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交易对">
              <el-input :value="editForm.symbol" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方向">
              <el-tag :type="editForm.side === 'long' ? 'success' : 'danger'">
                {{ editForm.side === 'long' ? '做多' : '做空' }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="止损价格" prop="stopLoss">
              <el-input-number 
                v-model="editForm.stopLoss" 
                :precision="getPricePrecision(editForm.symbol)"
                :step="0.01"
                placeholder="设置止损价格"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="止盈价格" prop="takeProfit">
              <el-input-number 
                v-model="editForm.takeProfit" 
                :precision="getPricePrecision(editForm.symbol)"
                :step="0.01"
                placeholder="设置止盈价格"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="移动止损">
              <el-switch v-model="editForm.trailingStop" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自动平仓">
              <el-switch v-model="editForm.autoClose" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditClose">取消</el-button>
          <el-button type="primary" @click="saveEdit" :loading="editLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog 
      v-model="closeDialogVisible" 
      title="确认平仓" 
      width="500px"
    >
      <div class="close-confirm-content">
        <el-icon class="warning-icon"><Warning /></el-icon>
                 <div class="confirm-text">
           <p>确定要平仓以下持仓吗？</p>
           <div class="position-summary" v-if="currentClosePosition">
             <p><strong>{{ currentClosePosition.symbol }}</strong> - {{ currentClosePosition.side === 'long' ? '做多' : '做空' }}</p>
             <p>数量: {{ formatNumber(currentClosePosition.size) }}</p>
             <p>当前盈亏: 
               <span :class="currentClosePosition.pnl >= 0 ? 'profit-text' : 'loss-text'">
                 ${{ formatNumber(currentClosePosition.pnl) }}
               </span>
             </p>
           </div>
         </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmClose" :loading="closeLoading">
            确认平仓
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog 
      v-model="showBatchClose" 
      title="批量平仓" 
      width="600px"
    >
      <div class="batch-close-content">
        <p>确定要平仓以下 {{ selectedPositions.length }} 个持仓吗？</p>
        <el-table :data="selectedPositions" size="small" max-height="300">
          <el-table-column label="交易对" prop="symbol" width="100" />
          <el-table-column label="方向" width="80">
            <template #default="{ row }">
              <el-tag :type="row.side === 'long' ? 'success' : 'danger'" size="small">
                {{ row.side === 'long' ? '多' : '空' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="盈亏" width="120">
            <template #default="{ row }">
              <span :class="row.pnl >= 0 ? 'profit-text' : 'loss-text'">
                ${{ formatNumber(row.pnl) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showBatchClose = false">取消</el-button>
          <el-button type="danger" @click="confirmBatchClose" :loading="batchCloseLoading">
            确认批量平仓
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Wallet, TrendCharts, Money, Opportunity, PieChart, Warning, 
  Refresh, Close, Edit
} from '@element-plus/icons-vue'
import { 
  fetchPositions, 
  fetchPositionSummary, 
  closePosition as closePositionApi,
  updateStopLoss,
  updateTakeProfit,
  type Position, 
  type PositionSummary 
} from '@/mock/positionData'

// 响应式数据
const positions = ref<Position[]>([])
const summary = ref<PositionSummary | null>(null)
const selectedPositions = ref<Position[]>([])
const summaryLoading = ref(false)
const tableLoading = ref(false)
const editDialogVisible = ref(false)
const closeDialogVisible = ref(false)
const showBatchClose = ref(false)
const editLoading = ref(false)
const closeLoading = ref(false)
const batchCloseLoading = ref(false)

// 编辑表单
const editForm = reactive({
  id: 0,
  symbol: '',
  side: 'long' as 'long' | 'short',
  stopLoss: undefined as number | undefined,
  takeProfit: undefined as number | undefined,
  trailingStop: false,
  autoClose: false
})

const currentClosePosition = ref<Position | null>(null)
const editFormRef = ref()

// 表单验证规则
const editRules = {
  stopLoss: [
    { type: 'number', message: '请输入有效的价格', trigger: 'blur' }
  ],
  takeProfit: [
    { type: 'number', message: '请输入有效的价格', trigger: 'blur' }
  ]
}

// 初始化数据
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  await Promise.all([
    loadSummary(),
    loadPositions()
  ])
}

// 加载统计数据
const loadSummary = async () => {
  summaryLoading.value = true
  try {
    summary.value = await fetchPositionSummary()
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  } finally {
    summaryLoading.value = false
  }
}

// 加载持仓列表
const loadPositions = async () => {
  tableLoading.value = true
  try {
    positions.value = await fetchPositions()
  } catch (error) {
    ElMessage.error('加载持仓数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  loadData()
  ElMessage.success('数据已刷新')
}

// 选择变化处理
const handleSelectionChange = (selection: Position[]) => {
  selectedPositions.value = selection.filter(pos => pos.status === 'active')
}

// 编辑持仓
const editPosition = (position: Position) => {
  Object.assign(editForm, {
    id: position.id,
    symbol: position.symbol,
    side: position.side,
    stopLoss: position.stopLoss,
    takeProfit: position.takeProfit,
    trailingStop: position.trailingStop || false,
    autoClose: position.autoClose || false
  })
  editDialogVisible.value = true
}

// 保存编辑
const saveEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    // 更新止损和止盈
    if (editForm.stopLoss !== undefined) {
      await updateStopLoss(editForm.id, editForm.stopLoss)
    }
    if (editForm.takeProfit !== undefined) {
      await updateTakeProfit(editForm.id, editForm.takeProfit)
    }
    
    // 更新本地数据
    const position = positions.value.find(p => p.id === editForm.id)
    if (position) {
      position.stopLoss = editForm.stopLoss
      position.takeProfit = editForm.takeProfit
      position.trailingStop = editForm.trailingStop
      position.autoClose = editForm.autoClose
    }
    
    ElMessage.success('持仓设置已更新')
    editDialogVisible.value = false
  } catch (error) {
    ElMessage.error('更新失败，请重试')
  } finally {
    editLoading.value = false
  }
}

// 关闭编辑对话框
const handleEditClose = () => {
  editDialogVisible.value = false
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 平仓操作
const handleClosePosition = (position: Position) => {
  currentClosePosition.value = position
  closeDialogVisible.value = true
}

// 确认平仓
const confirmClose = async () => {
  if (!currentClosePosition.value) return
  
  closeLoading.value = true
  try {
    await closePositionApi(currentClosePosition.value.id)
    
    // 更新本地数据
    const index = positions.value.findIndex(p => p.id === currentClosePosition.value!.id)
    if (index !== -1) {
      positions.value[index].status = 'closed'
    }
    
    ElMessage.success('持仓已平仓')
    closeDialogVisible.value = false
    loadSummary() // 重新加载统计数据
  } catch (error) {
    ElMessage.error('平仓失败，请重试')
  } finally {
    closeLoading.value = false
  }
}

// 批量平仓
const confirmBatchClose = async () => {
  batchCloseLoading.value = true
  try {
    const promises = selectedPositions.value.map(pos => closePositionApi(pos.id))
    await Promise.all(promises)
    
    // 更新本地数据
    selectedPositions.value.forEach(pos => {
      const index = positions.value.findIndex(p => p.id === pos.id)
      if (index !== -1) {
        positions.value[index].status = 'closed'
      }
    })
    
    ElMessage.success(`已成功平仓 ${selectedPositions.value.length} 个持仓`)
    showBatchClose.value = false
    selectedPositions.value = []
    loadSummary() // 重新加载统计数据
  } catch (error) {
    ElMessage.error('批量平仓失败，请重试')
  } finally {
    batchCloseLoading.value = false
  }
}

// 工具函数
const formatNumber = (num: number): string => {
  return Math.abs(num) >= 1000 
    ? (num / 1000).toFixed(1) + 'K'
    : num.toFixed(2)
}

const formatPrice = (price: number): string => {
  return price < 1 ? price.toFixed(4) : price.toFixed(2)
}

const formatPercent = (ratio: number): string => {
  return (ratio * 100).toFixed(2) + '%'
}

const formatDateTime = (dateStr: string): string => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const getPricePrecision = (symbol: string): number => {
  return symbol.includes('USDT') && !symbol.startsWith('BTC') && !symbol.startsWith('ETH') ? 4 : 2
}

const getRiskLevelClass = (level?: string): string => {
  switch (level) {
    case 'low': return 'safe'
    case 'medium': return 'warning'
    case 'high': return 'danger'
    default: return 'info'
  }
}

const getStatusType = (status: string): string => {
  switch (status) {
    case 'active': return 'success'
    case 'closing': return 'warning'
    case 'closed': return 'info'
    default: return 'info'
  }
}

const getStatusText = (status: string): string => {
  switch (status) {
    case 'active': return '活跃'
    case 'closing': return '平仓中'
    case 'closed': return '已平仓'
    default: return '未知'
  }
}

const getPriceChangeClass = (entryPrice: number, currentPrice: number, side: string): string => {
  const isProfit = (side === 'long' && currentPrice > entryPrice) || 
                   (side === 'short' && currentPrice < entryPrice)
  return isProfit ? 'profit-text' : 'loss-text'
}
</script>

<style lang="scss" scoped>
.positions-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  
  h1 {
    font-size: 28px;
    font-weight: 600;
    color: #1f2937;
    margin: 0 0 8px 0;
  }
  
  p {
    color: #6b7280;
    margin: 0;
    font-size: 14px;
  }
}

.summary-cards {
  margin-bottom: 20px;
  
  .summary-card {
    height: 100px;
    border: none;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    :deep(.el-card__body) {
      padding: 0;
      height: 100%;
    }
    
    .card-content {
      display: flex;
      align-items: center;
      height: 100%;
      padding: 20px;
      
      .card-icon {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        
        .el-icon {
          font-size: 24px;
          color: white;
        }
        
        &.total {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        &.active {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        &.margin {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        &.profit {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
        
        &.loss {
          background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }
        
        &.safe {
          background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
        }
        
        &.warning {
          background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
        }
        
        &.danger {
          background: linear-gradient(135deg, #ff8a80 0%, #ea4c89 100%);
        }
      }
      
      .card-info {
        flex: 1;
        
        .card-value {
          font-size: 24px;
          font-weight: 600;
          color: #1f2937;
          line-height: 1;
          margin-bottom: 5px;
          
          &.profit-text {
            color: #10b981;
          }
          
          &.loss-text {
            color: #ef4444;
          }
        }
        
        .card-label {
          font-size: 12px;
          color: #6b7280;
          font-weight: 500;
        }
      }
    }
  }
}

.positions-table-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
}

.positions-table {
  .coin-info {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .coin-icon {
      font-size: 20px;
      width: 30px;
      text-align: center;
    }
    
    .coin-details {
      .coin-symbol {
        font-weight: 600;
        color: #1f2937;
        font-size: 14px;
      }
      
      .coin-name {
        font-size: 12px;
        color: #6b7280;
      }
    }
  }
  
  .pnl-info {
    .pnl-percent {
      font-size: 12px;
      margin-top: 2px;
    }
  }
  
  .profit-text {
    color: #10b981;
    font-weight: 600;
  }
  
  .loss-text {
    color: #ef4444;
    font-weight: 600;
  }
  
  .liquidation-price {
    color: #f59e0b;
    font-weight: 500;
  }
  
  .strategy-info {
    .strategy-name {
      font-size: 13px;
      color: #1f2937;
      font-weight: 500;
    }
    
    .exchange-name {
      font-size: 12px;
      color: #6b7280;
      margin-top: 2px;
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }
}

.close-confirm-content {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  
  .warning-icon {
    font-size: 24px;
    color: #f59e0b;
    margin-top: 5px;
  }
  
  .confirm-text {
    flex: 1;
    
    .position-summary {
      background: #f9fafb;
      padding: 15px;
      border-radius: 8px;
      margin-top: 15px;
      border-left: 4px solid #3b82f6;
      
      p {
        margin: 5px 0;
        font-size: 14px;
      }
    }
  }
}

.batch-close-content {
  p {
    margin-bottom: 15px;
    font-size: 14px;
    color: #374151;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .positions-page {
    padding: 15px;
  }
  
  .summary-cards {
    :deep(.el-col) {
      margin-bottom: 15px;
    }
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start !important;
    
    .header-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .positions-table {
    font-size: 12px;
    
    .action-buttons {
      flex-direction: column;
      gap: 5px;
    }
  }
}
</style>
